<template>
  <div class="yoyo-container mx-auto min-h-screen">
    <!-- 头部导航 -->
    <navBar :title="isEdit ? $t('bankCard.editBankCard') : $t('bankCard.addBankCard')"></navBar>

    <!-- 表单内容 -->
    <div class="bg-white rounded-lg mx-4 mt-3">
      <van-field v-model="form.name" :label="$t('bankCard.name')" :placeholder="$t('bankCard.namePlaceholder')" />
      <van-field v-model="form.cardNo" :label="$t('bankCard.cardNo')" :placeholder="$t('bankCard.cardNoPlaceholder')" />
      <van-field 
        v-model="form.expireDate" 
        :label="$t('bankCard.expireDate')" 
        :placeholder="$t('bankCard.expireDatePlaceholder')"
        readonly
        is-link
        @click="showDatePicker = true" />
      <van-field v-model="form.checksum" :label="$t('bankCard.checksum')" :placeholder="$t('bankCard.checksumPlaceholder')" />
    </div>

    <!-- 设为默认银行卡 -->
    <div class="bg-white rounded-lg mx-4 mt-2 p-3 flex items-center justify-between">
      <span class="text-[#646566] text-sm">{{ $t("bankCard.setAsDefault") }}</span>
      <van-switch v-model="form.defaultStatus" size="20px" active-color="#ff7a00" />
    </div>
    
    <van-button type="primary" round @click="handleSave" class="mx-16 w-[calc(100%-8rem)] mb-4 mt-10 bg-orange-500 border-orange-500">
      {{ $t("bankCard.save") }}
    </van-button>

    <van-button
      v-if="isEdit"
      plain
      round
      type="danger"
      @click="handleDelete"
      class="mx-16 w-[calc(100%-8rem)] mb-3 text-[#ff7a00] border-orange-500">
      {{ $t("bankCard.delete") }}
    </van-button>

    <van-popup v-model="showDatePicker" position="bottom">
      <van-datetime-picker v-model="selectedDate" type="year-month" @confirm="onDateConfirm" @cancel="showDatePopup = false" />
    </van-popup>
  </div>
</template>

<script>
import { Field, Button, Switch, Popup, DatetimePicker, Toast, Dialog } from "vant"
import { addBank, updateBank, deleteBank, getBankDetail } from "@/apis/userInfo"
import { mapGetters } from "vuex"

export default {
  name: "BankCard",
  components: {
    [Field.name]: Field,
    [Button.name]: Button,
    [Switch.name]: Switch,
    [Popup.name]: Popup,
    [DatetimePicker.name]: DatetimePicker,
  },
  data() {
    return {
      loading: false,
      showDatePicker: false,
      selectedDate: new Date(),
      form: {
        name: "",
        cardNo: "",
        expireDate: "",
        checksum: "",
        defaultStatus: false,
      },
    }
  },
  computed: {
    isEdit() {
      return !!this.$route.query.id
    },
    ...mapGetters({
      isLoggedIn: "auth/isLoggedIn",
    }),
  },
  created() {
    if (this.isEdit) {
      this.loadBankCardData()
    }
  },
  methods: {
    // 加载银行卡数据（编辑模式）
    async loadBankCardData() {
      try {
        const response = await getBankDetail({ id: this.$route.query.id })
        this.form = response.data
      } catch (error) {
        console.error("获取银行卡失败:", error)
      }
    },

    // 日期确认
    onDateConfirm(value) {
      const year = value.getFullYear()
      const month = String(value.getMonth() + 1).padStart(2, '0')
      this.form.expireDate = `${year}-${month}`
      this.showDatePicker = false
    },

    // 保存银行卡
    async handleSave() {
      if (!this.validateForm()) {
        return
      }

      try {
        if (this.isEdit) {
          await updateBank({
            id: this.$route.query.id,
            ...this.form,
          })
          Toast.success(this.$t("bankCard.updateSuccess"))
        } else {
          await addBank(this.form)
          Toast.success(this.$t("bankCard.addSuccess"))
        }

        // 返回上一页
        setTimeout(() => {
          this.$router.go(-1)
        }, 1000)
      } catch (error) {
        console.error("保存银行卡失败:", error)
      }
    },

    // 删除银行卡
    async handleDelete() {
      try {
        await Dialog.confirm({
          title: this.$t("bankCard.deleteConfirm"),
          message: this.$t("bankCard.deleteMessage"),
        })

        await deleteBank({ id: this.$route.query.id })
        Toast.success(this.$t("bankCard.deleteSuccess"))

        setTimeout(() => {
          this.$router.go(-1)
        }, 1000)
      } catch (error) {
        if (error !== "cancel") {
          console.error("删除银行卡失败:", error)
          Toast(this.$t("bankCard.deleteError"))
        }
      }
    },

    // 表单验证
    validateForm() {
      if (!this.form.name) {
        Toast(this.$t("bankCard.nameRequired"))
        return false
      }
      if (!this.form.cardNo) {
        Toast(this.$t("bankCard.cardNoRequired"))
        return false
      }
      if (!this.form.expireDate) {
        Toast(this.$t("bankCard.expireDateRequired"))
        return false
      }
      if (!this.form.checksum) {
        Toast(this.$t("bankCard.checksumRequired"))
        return false
      }
      return true
    },
  },
  watch: {
    isLoggedIn: {
      handler(newVal) {
        if (newVal && this.$route.path === "/bank-card") {
          this.loadBankCardData()
        }
      },
      deep: true,
      immediate: false,
    },
  },
}
</script>

<style scoped>
/* 自定义样式 */
.van-field__label {
  color: #333;
  font-weight: 500;
}

.van-field__control {
  color: #666;
}

.van-field__control::placeholder {
  color: #ccc;
}

/deep/.van-cell {
  background-color: transparent;
}
/deep/.van-field__control {
  text-align: right;
}
</style>